package com.gitee.lougnib.hellowebim.module.chatroom.service;

import static com.gitee.lougnib.hellowebim.common.mybatis.mapper.ChatRoomMessageEntityDynamicSqlSupport.*;
import static org.mybatis.dynamic.sql.SqlBuilder.*;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.mybatis.dynamic.sql.render.RenderingStrategies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gitee.lougnib.hellowebim.common.dao.CommonDao;
import com.gitee.lougnib.hellowebim.common.mybatis.entity.ChatRoomMessageEntity;
import com.gitee.lougnib.hellowebim.common.mybatis.mapper.ChatRoomMessageMapper;
import com.gitee.lougnib.hellowebim.module.chatroom.constant.ChatRoomConsts;

@Service
public class ChatRoomService {

    @Autowired
    private ChatRoomMessageMapper chatRoomMessageMapper;

    @Autowired
    private CommonDao commonDao;

    public List<ChatRoomMessageEntity> getAllMessages() {
        return getNewestMessages(0L);
    }

    @Transactional
    public Long saveMessage(String senderId, String messageContent) {
        if (StringUtils.isBlank(messageContent)) {
            return -1L;
        }

        ChatRoomMessageEntity message = new ChatRoomMessageEntity();

        message.setSendTime(System.currentTimeMillis());
        message.setChatRoomId(getChatRoomId());
        message.setSenderId(Long.parseLong(senderId));
        message.setMessageType(1); // 1: 文本
        message.setMessageContent(messageContent);
        chatRoomMessageMapper.insertSelective(message);
        return commonDao.selectLastInsertId();
    }

    public List<ChatRoomMessageEntity> getNewestMessages(Long lastMessageId) {
        return chatRoomMessageMapper.selectMany(select(id, messageContent, sendTime, senderId)
                .from(chatRoomMessageEntity).where(id, isGreaterThan(lastMessageId)).and(chatRoomId, isEqualTo(getChatRoomId())).build()
                .render(RenderingStrategies.MYBATIS3));
    }

    public void removeOldMessages() {
        // 48 小时前的时间
        long oldSendTime = System.currentTimeMillis() - 48 * 60 * 60 * 1000;
        chatRoomMessageMapper.delete(deleteFrom(chatRoomMessageEntity).where(sendTime, isLessThan(oldSendTime)).build()
                .render(RenderingStrategies.MYBATIS3));
    }

    private Long getChatRoomId() {
        return ChatRoomConsts.DEFAULT_CHAT_ROOM_ID;
    }
}
